package com.edaoe.module.resource;

import com.edaoe.interceptor.AuthInterceptor;
import com.edaoe.util.FileUtil;
import com.edaoe.util.HttpUtil;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.kit.PropKit;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * Created by Dull on 2017/3/25 0025.
 */
public class ResourceController extends Controller{

    public void show(){
        String filePath=getPara("file");
        String[] filePathArr=filePath.split("-");
        String userIdStr=filePathArr[0];
        String fileName=filePathArr[1];
        File file=new File(PropKit.get("baseUploadPath")+"/"+userIdStr+"/"+fileName);
        renderFile(file);
    }

    @Before(AuthInterceptor.class)
    public void uploadForMDEditor() throws UnsupportedEncodingException {
        Long userId = getAttr("userId");
        String uploadPath="/"+userId;
        String fileName=FileUtil.renameToUUID(getFile("editormd-image-file",uploadPath));
        StringBuilder sb=new StringBuilder();
        sb.append(getPara("callback"))
                .append("?dialog_id=")
                .append(getPara("dialog_id"))
                .append("&success=1&message=")
                .append(URLEncoder.encode("上传成功！","UTF-8"))
                .append("&url=")
                .append(HttpUtil.getServerUrl(getRequest()))
                .append("/resource/show?file=")
                .append(userId)
                .append("-")
                .append(fileName);
        redirect(sb.toString());
    }

}
